﻿Imports System.IO
Imports System.Xml


Module DS3

    Private xmlDoc As New XmlDocument 'fuente

    Private dirXML As String
    Private usrXML As String
    Private passXML As String

    Private dirWAV As String
    Private usrWAV As String
    Private passWAV As String

    Private imper As Boolean
    Private imper2 As Boolean

    Private dirLog As String
    Private dirTemp As String
    Private FTPTimeOut As Integer
    Private dirInstall As String
    Private dirFTP As String
    Private archXml2 As String 'Archivo Template
    Private conf As Boolean



    Sub inicializar()

        Try
            Dim xmldoc As New XmlDocument()
            Dim a As String
            Dim b As Integer


            Try
                dirInstall = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Anew\AppQfinitiExport", "dirInstall", Nothing).ToString.Trim
            Catch ex As Exception
                dirInstall = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Wow6432Node\Anew\AppQfinitiExport", "dirInstall", Nothing).ToString.Trim
            End Try


            xmldoc.Load(dirInstall & "ConfigAppExport.xml")



            a = xmldoc.SelectSingleNode("/CONFIG/INFODATA/PATH").InnerXml
            b = a.Length
            If InStr(a, "\\") = 0 Then
                If InStr(b - 1, a, "\") = 0 Then
                    dirXML = a.Insert(b, "\")
                Else
                    dirXML = a
                End If
                usrXML = ""
                passXML = ""
                imper = False
            Else
                dirXML = a
                usrXML = xmldoc.SelectSingleNode("/CONFIG/INFODATA/USER").InnerXml
                passXML = xmldoc.SelectSingleNode("/CONFIG/INFODATA/PASS").InnerXml
                imper = True
            End If


            a = xmldoc.SelectSingleNode("/CONFIG/INFOWAV/PATH").InnerXml
            b = a.Length
            If InStr(a, "\\") = 0 Then
                If InStr(b - 1, a, "\") = 0 Then
                    dirWAV = a.Insert(b, "\")
                Else
                    dirWAV = a
                End If
                usrWAV = ""
                passWAV = ""
                imper2 = False
            Else
                dirWAV = a
                usrWAV = xmldoc.SelectSingleNode("/CONFIG/INFOWAV/USER").InnerXml
                passWAV = xmldoc.SelectSingleNode("/CONFIG/INFOWAV/PASS").InnerXml
                imper2 = True
            End If


            a = xmldoc.SelectSingleNode("/CONFIG/INFOLOG/DIRLOG").InnerXml
            b = a.Length
            If a = "" Then
                dirLog = dirInstall
            Else
                If InStr(b - 1, a, "\") = 0 Then
                    dirLog = a.Insert(b, "\")
                Else
                    dirLog = a
                End If
            End If


        Catch ex As Exception

            log(ex.Message)
            dirXML = "C:\ToExport\"
            dirLog = dirInstall & "Logs"

        End Try


    End Sub

    Sub Main()

        inicializar()
        archXml2 = dirInstall & "Data.xml"

        dirFTP = dirInstall & "FTP\"
        dirTemp = dirInstall & "tmp\"

        Try
            My.Computer.FileSystem.CopyFile(dirInstall & "Template.xml", archXml2, True)

            Try
                Dim impersonator As New AliasAccount(usrXML, passXML)
                impersonator.BeginImpersonation()
                Dim dir As DirectoryInfo = New DirectoryInfo(dirXML)
                If dir.Exists Then
                    For Each fi As FileInfo In dir.GetFiles("*.xml", SearchOption.TopDirectoryOnly)
                        fi.CopyTo(dirTemp & fi.Name, True)
                        XMLCreate(dirTemp & fi.Name)
                        conf = True
                        Try
                            fi.Delete()
                            log("Archivo " & fi.DirectoryName & "\" & fi.Name & " borrado")
                        Catch ex As Exception
                            log("No se pudo borrar el archivo: " & fi.DirectoryName & "\" & fi.Name)
                            log(ex.Message)
                        End Try
                    Next
                Else
                    Console.WriteLine("Ruta especificada o credenciales no validas")
                End If

                impersonator.EndImpersonation()
                impersonator = Nothing
                releaseObject(impersonator)

            Catch ex As Exception
                log(ex.Message)
                Console.WriteLine("Error Rutina: Main durante impersonificacion")
            End Try


            If conf = True Then
                My.Computer.FileSystem.MoveFile(archXml2, dirFTP & "Data.xml", True)
            End If

        Catch ex As Exception
            log(ex.Message)
            log("Error en la rutina Main")
            Exit Sub
        End Try
    End Sub


    Sub XMLCreate(ByVal archXml As String)
        log("XMLCreate")

        Dim b As Integer = 0
        Dim c As String = "" 'rec_key o trans_id
        Dim n As Integer = 1
        Dim n2 As Integer = 2
        Dim numwav As Integer = 0
        Dim fileWAV As String = ""
        Dim org As Integer = 0
        Dim l As Integer = 0
        Dim iz As String
        Dim der As String
        Dim objProcess As System.Diagnostics.Process = New System.Diagnostics.Process()

        Dim DXML As New DataXML

        Dim lazo As Boolean = True
        Dim dir As String = ""

        Dim durWav As String
        Dim intPto As Integer

        Dim xmlNodes As XmlNodeList
        Dim xmlNode As XmlNode

        Dim impersonator2 As New AliasAccount(usrWAV, passWAV)

        objProcess.StartInfo.FileName = dirInstall & "sox\sox.exe"
        objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        objProcess.StartInfo.UseShellExecute = False



        Try
            xmlDoc.Load(archXml)

            xmlNodes = xmlDoc.GetElementsByTagName("transaction")


            'manejar errores
            For Each xmlNode In xmlNodes
               
                If lazo = True Then
                    c = xmlNode.Attributes("trans_id").Value.Trim
                    dir = xmlNode.Attributes("filepath").Value.Trim
                    dir = dirWAV & dir
                    numwav = 0

                    impersonator2.BeginImpersonation()
                    Dim dr As DirectoryInfo = New DirectoryInfo(dir)
                    If dr.Exists Then
                        For Each fi As FileInfo In dr.GetFiles("*" & c & "*.wav", SearchOption.TopDirectoryOnly)
                            Try
                                fi.CopyTo(dirTemp + fi.Name, True)
                                numwav = numwav + 1
                                fileWAV = dirTemp + fi.Name
                            Catch ex As Exception
                                log("Problema con el copiado del archivo: " & fi.DirectoryName & "\" & fi.Name)
                                log(ex.Message)
                            End Try

                        Next
                    Else
                        Console.WriteLine("Ruta especificada o credenciales no validas")
                    End If
                    impersonator2.EndImpersonation()



                    log("Archivos WAV encontrados para el TransID " & c & ": " & numwav)

                    If numwav > 1 Then
                        lazo = False
                        durWav = ""
                        intPto = 0
                        Try
                            org = InStr(fileWAV, c)
                            l = Len(fileWAV)
                            fileWAV = Left(fileWAV, l - 7) & "500.wav"
                            iz = Left(fileWAV, org - 2)
                            der = Right(fileWAV, l - org + 1)

                            fileWAV = iz & "0" & der

                            My.Computer.FileSystem.RenameFile(fileWAV, "TEMP0.wav")
                            log("Archivo " & fileWAV & " renombrado a " & dirTemp & "TEMP0.wav")
                            For numL = 1 To numwav - 1
                                Try
                                    For Each audio As String In My.Computer.FileSystem.GetFiles(dirTemp, FileIO.SearchOption.SearchTopLevelOnly, "*" & numL & c & "*.wav")

                                        objProcess.StartInfo.RedirectStandardOutput = False
                                        objProcess.StartInfo.Arguments = " --multi-threaded --combine concatenate " & Chr(34) & dirTemp & "TEMP" & numL - 1 & ".wav" & Chr(34) & " " & Chr(34) & audio & Chr(34) & " " & Chr(34) & dirTemp & "TEMP" & numL & ".wav" & Chr(34) & " --norm gain -e"
                                        objProcess.Start()
                                        objProcess.WaitForExit()
                                        objProcess.Close()
                                        log("Archivo fusionados " & dirTemp & "TEMP" & numL - 1 & ".wav con " & audio & " resultante en " & dirTemp & "TEMP" & numL)

                                    Next

                                Catch ex As Exception
                                    log(ex.Message)
                                End Try

                            Next numL

                            fileWAV = c & ".wav"
                            My.Computer.FileSystem.RenameFile(dirTemp & "TEMP" & numwav - 1 & ".wav", fileWAV)

                            log("Archivo " & fileWAV & " creado")

                            objProcess.StartInfo.RedirectStandardOutput = True
                            objProcess.StartInfo.Arguments = " --i -D  " & Chr(34) & dirTemp & fileWAV & Chr(34)
                            objProcess.Start()

                            durWav = objProcess.StandardOutput.ReadToEnd
                            intPto = InStr(durWav, ".")
                            durWav = durWav.Remove(intPto - 1)


                            With DXML
                                .TransID = c
                                .Agent = xmlNode.Attributes("agent").Value.Trim
                                .pDate = xmlNode.Attributes("date").Value.Trim
                                .pTime = xmlNode.Attributes("time").Value.Trim
                                .Duration = durWav
                                .DNIS = xmlNode.Attributes("dnis").Value.Trim
                                .ANI = xmlNode.Attributes("ANI").Value.Trim
                                .Status = "OK"
                                .Connid = xmlNode.Attributes("connid").Value.Trim
                                .CallDirection = xmlNode.Attributes("call_direction").Value.Trim
                                .NameFile = fileWAV
                            End With

                            If DXML.WriteXML(archXml2) Then
                                n2 = n2 + 1
                                My.Computer.FileSystem.MoveFile(dirTemp & fileWAV, dirFTP & fileWAV, True)

                                For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirTemp, FileIO.SearchOption.SearchTopLevelOnly, "*.wav")
                                    Try
                                        My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                                        log("Archivo " & foundFile & " borrado")
                                    Catch ex As Exception
                                        log(ex.Message)
                                    End Try
                                Next
                            Else
                                n2 = n2 + 1
                                log("Problemas al crear archivo XML para trans_id: " & c)
                            End If


                        Catch ex As Exception
                            log(ex.Message)
                            log("Error al procesar archivo WAV asociado al TransID: " & c)
                        End Try




                    ElseIf numwav = 1 Then
                        Try
                            durWav = ""
                            intPto = 0

                            objProcess.StartInfo.RedirectStandardOutput = True
                            objProcess.StartInfo.Arguments = " --i -D  " & Chr(34) & fileWAV & Chr(34)
                            objProcess.Start()

                            durWav = objProcess.StandardOutput.ReadToEnd
                            intPto = InStr(durWav, ".")
                            durWav = durWav.Remove(intPto - 1)


                            fileWAV = fileWAV.Replace(dirTemp, "")

                            With DXML
                                .TransID = c
                                .Agent = xmlNode.Attributes("agent").Value.Trim
                                .pDate = xmlNode.Attributes("date").Value.Trim
                                .pTime = xmlNode.Attributes("time").Value.Trim
                                .Duration = durWav
                                .DNIS = xmlNode.Attributes("dnis").Value.Trim
                                .ANI = xmlNode.Attributes("ANI").Value.Trim
                                .Status = "OK"
                                .Connid = xmlNode.Attributes("connid").Value.Trim
                                .CallDirection = xmlNode.Attributes("call_direction").Value.Trim
                                .NameFile = fileWAV
                            End With

                            If DXML.WriteXML(archXml2) Then
                                n2 = n2 + 1
                                My.Computer.FileSystem.MoveFile(dirTemp & fileWAV, dirFTP & fileWAV, True)
                            Else
                                n2 = n2 + 1
                                log("Problemas al crear archivo XML para trans_id: " & c)
                            End If


                        Catch ex As Exception
                            log(ex.Message)
                            log("Error al procesar archivo WAV asociado al TransID: " & c)
                        End Try

                    End If

                Else
                    n = n + 1
                    If n = numwav Then
                        lazo = True
                        n = 1
                    End If

                End If

                fileWAV = ""

            Next


           
            xmlNode = Nothing
            xmlNodes = Nothing
            xmlDoc = Nothing

            releaseObject(xmlNode)
            releaseObject(xmlNodes)
            releaseObject(xmlDoc)


            impersonator2 = Nothing
            releaseObject(impersonator2)
          

            For Each foundFile As String In My.Computer.FileSystem.GetFiles(dirTemp, FileIO.SearchOption.SearchTopLevelOnly, "*.*")
                Try
                    My.Computer.FileSystem.DeleteFile(foundFile, FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
                    log("Archivo " & foundFile & " borrado")
                Catch ex As Exception
                    log("No se pudo borrar el archivo: " & foundFile)
                    log(ex.Message)
                End Try
            Next

            objProcess = Nothing
            releaseObject(objProcess)

        Catch ex As Exception
            log(ex.Message)

            xmlNode = Nothing
            xmlNodes = Nothing
            xmlDoc = Nothing

            releaseObject(xmlNode)
            releaseObject(xmlNodes)
            releaseObject(xmlDoc)

            objProcess = Nothing
            releaseObject(objProcess)

            impersonator2 = Nothing
            releaseObject(impersonator2)
        End Try


    End Sub


    Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

    Function FechayHora() As String
        FechayHora = Now.Date.ToString.Remove(InStr(Now.Date.ToString, " ")) & Now.TimeOfDay.ToString
    End Function

    Sub log(ByVal mensaje As String)
        Try
            Dim oSW As New StreamWriter(dirInstall & "AppQfinitiExport.log", True)
            oSW.WriteLine(FechayHora() & " " & mensaje)
            oSW.Flush()
            oSW.Close()
            releaseObject(oSW)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

End Module
